import {app, BrowserWindow, dialog, ipcMain} from 'electron';
import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import DBStore from './modules/database/db.js';

const encryptAlgorithm = 'RSA-SHA512';
const encryptPassword = 'cxfh@vip.sina.com';

let appStorePath = path.join(app.getPath('appData'), 'riskmonitor');
global.db = new DBStore(appStorePath);
global.WindowManager = new Map();
global.DataCache = new Map();
let defaultWindowArgs = {
  name: 'window' + WindowManager.size,
	width: 950,
	height: 650,
	'min-width': 950,
	'min-height': 650,
	'use-content-size': true,
	debug: false,
	url: 'default.html'
};

function CleanAndQuit() {
  DB.Kl.remove({name: 'unlock_flag'}, {}, function(err) {
    DB.compactDatabases().then(() => {
      app.quit();
    });
  });
}

function OpenWindow(winArgs = defaultWindowArgs) {
  let options = winArgs;
  options.url = 'file://'.concat(path.join(__dirname, '..', options.url));
  WindowManager.set(options.name, new BrowserWindow({
    width: options.width,
    height: options.height,
    'min-width': options['min-width'],
    'min-height': options['min-height'],
    'use-content-size': options['use-content-size']
  }));
  if (options.debug) WindowManager.get(options.name).openDevTools();
  WindowManager.get(options.name).loadURL(options.url);
  WindowManager.get(options.name).on('closed', () => {
    WindowManager.delete(options.name);
  });
}

ipcMain.on('quit-app', (event, arg) => {
  CleanAndQuit();
});
ipcMain.on('open-window', (event, arg) => {
  OpenWindow(arg);
});
ipcMain.on('route-message', (event, arg) => {
  ipcMain.send(arg.evt, arg.msg);
});
ipcMain.on('store-in-cache', (event, arg) => {
  DataCache.set(arg.name, arg.data);
});
ipcMain.on('fetch-from-cache', (event, arg) => {
  if (DataCache.has(arg)) {
    event.returnValue = DataCache.get(arg);
    DataCache.delete(arg);
  }
});
ipcMain.on('print-content', (event, arg = {
  windowName: 'anonymous',
  options: {
    silent: false,
    printBackground: false
  }
}) => {
  if (!WindowManager.has(arg.windowName)) return;
  let reqWindowContent = WindowManager.get(arg.windowName).webContents;
  reqWindowContent.print(arg.options);
});

app.on('window-all-closed', () => {
  CleanAndQuit();
});
app.on('ready', () => {
  if (!fs.existsSync(appStorePath)) fs.mkdirSync(appStorePath);
  fs
	.readdirSync(path.join(__dirname, 'assets'))
	.filter((file) => {
		return (file.indexOf('.') !== 0) && (file.endsWith('.db'));
	})
	.forEach((file) => {
		fs.readFile(path.join(appStorePath, file), (err, data) => {
			if (err || data.length === 0) {
				fs.readFile(path.join(__dirname, 'assets', file), (err, data) => {
					if (err) throw err;
					fs.writeFile(path.join(appStorePath, file), data);
				});
			}
		});
	});

  new Promise((resolve, reject) => {
    db.dl.count({name: 'password'}, (err, count) => {
      if (err) {
        reject('login db error');
      } else if (count === 0) {
        let h = crypto.createHmac(encryptAlgorithm, encryptPassword);
        h.update('1234');
        db.dl.insert({
					name: 'password',
					kl: h.digest('hex')
				}, (err, doc) => {
					if (err) reject('login db error');
					resolve(0);
				});
      } else {
        resolve(0);
      }
    });
  })
  .then((code) => {
    return new Promise(function(resolve, reject) {
			db.dl.count({name: 'unlock_flag'}, (err, count) => {
				if (err) {
					reject('login db error');
				} else if (count === 0) {
					db.dl.insert({
						name: 'unlock_flag',
						unlocked: false,
						unlock_time: 0
					}, (err, doc) => {
						if (err) reject('login db error');
						resolve(0);
					});
				} else {
					resolve(0);
				}
			});
		});
  })
  .then((code) => {
    OpenWindow({
      name: 'mainWindow',
      debug: false,
      url: 'index.html'
    });
  })
  .catch((err) => {
    dialog.showMessageBox({
			type: 'error',
			buttons: ['知道了'],
			title: '数据库错误',
			message: '登录数据库初始化错误，需要联系供应商解决适应性故障。'
		}, () => {
			CleanAndQuit();
		});
  });
});
